﻿using housingsafety.server.Hawk;
using housingsafety.server.Svcs;
using HawkAuthentication;
using System.Linq;
using System.Threading.Tasks;

namespace housingsafety.server.SvcImpls
{
    internal class HawkCredentialProvider : IHawkCredentialProvider
    {
        private readonly IUserTokenService _userTokenService;
        public HawkCredentialProvider(IUserTokenService userTokenService)
        {
            this._userTokenService = userTokenService;
        }

        public Task<HawkCredential> GetKeyByKeyIdAsync(string keyId, string jwtHash)
        {
            if (string.IsNullOrEmpty(keyId) || string.IsNullOrEmpty(jwtHash))
            {
                return Task.FromResult<HawkCredential>(null);
            }

            var tokens = _userTokenService.GetRefreshTokens(keyId);
            if (!tokens.Succ)
            {
                return Task.FromResult<HawkCredential>(null);
            }

            if (tokens.Data.Tokens.ContainsKey(jwtHash))
            {
                return Task.FromResult(new HawkCredential()
                {
                    KeyId = keyId,
                    Key = tokens.Data.Tokens[jwtHash]
                });
            }

            return Task.FromResult<HawkCredential>(null);
        }
    }
}